package cn.edu.ysu.zry.network;

import cn.edu.ysu.zry.config.Config;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @program: XieyiBlockChainOS
 * @description: 请求其他socket的封装
 * @author: Ruiyuan Zhang
 * @create: 2020-04-20 22:28
 */
public class RequestPack {
    public static String ip;
    public static int port;
    public static <T> MessagePack request(MessagePack<T> msg){
        try{
            MessagePack<Object> res=null;
            // 建立socket连接
            Socket socket = new Socket(ip,port);

            // 获取输出流，向服务端发送数据
            OutputStream outputStream= socket.getOutputStream();
            JSONObject jsonObject=new JSONObject(msg);
            outputStream.write(jsonObject.toString().getBytes(Config.CHARACTER_ENCODING));
            socket.shutdownOutput(); // 告诉服务端我已经发送完毕数据了

            // 获取输入流，获取socket中的数据
            InputStream inputStream = socket.getInputStream();
            int len;
            byte[]bytes=new byte[1024];
            StringBuffer sb = new StringBuffer();
            while ((len=inputStream.read(bytes))!=-1) {
                sb.append(new String(bytes,0,len,Config.CHARACTER_ENCODING));
            }

            // 处理返回值
            if(sb!=null && sb.length()>0){
                JSONObject jsonResponse= new JSONObject(sb.toString());
                res=JSONUtil.toBean(jsonObject,MessagePack.class);
            }

            inputStream.close();
            outputStream.close();
            socket.close();
            return res;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
